﻿#region
using System;
using System.Threading;
using System.Windows.Forms;
using ComicsDownloader.Forms;

#endregion

namespace ComicsDownloader
{
    internal static class Program
    {
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RunTimeChecker.IsRunTime = true;

            Application.ThreadException += Application_ThreadException;

            SingleInstance instance = new SingleInstance("{CB4198CB-E9AA-4E03-B788-B2BC68C5AB26}");

            if (instance.IsRunning())
            {
                MessageBox.Show("이미 실행 중입니다.");
            }
            else
            {
                Application.Run(new MainForm());
            }
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            if (e.Exception.Message .Contains("The tasks argument contains no tasks."))
                return;

            MessageBox.Show(e.Exception.Message);
            if (e.Exception.InnerException != null)
                MessageBox.Show(e.Exception.InnerException.Message);
        }
    }

    public class RunTimeChecker
    {
        public static bool IsRunTime { get; set; }
    }

    public class SingleInstance
    {
        private readonly Mutex _mutex;

        public SingleInstance(string mutexname)
        {
            _mutex = new Mutex(false, mutexname);
        }

        public bool IsRunning()
        {
            return !_mutex.WaitOne(10, true);
        }
    }
}